<template>
  <!-- 1. 表单组件: uni-forms -->
  <uni-forms :model="formData" :rules="rules" validateTrigger='blur' class="login-form" ref="accountForm">
    <!-- z账号
     注意:name的值 要和  fomaData的属性名一致,将来效验用
     -->
    <uni-forms-item name="account">
      <uni-easyinput type="text" v-model="formData.account" placeholder="请输入账号" class="uni-input-input"
        placeholder-style="color: #818181" />
    </uni-forms-item>

    <!-- 密码 -->
    <uni-forms-item name="password">
      <uni-easyinput type="text" v-model="formData.password" placeholder="请输入密码" class="uni-input-input"
        placeholder-style="color: #818181" />
    </uni-forms-item>

    <button @click="onFormSubmit" class="submit-button">登录</button>
  </uni-forms>
</template>

<script setup>
  import { ref } from 'vue'
  import { loginApi } from '@/apis/user.js'
  import { useUserStore } from '@/stores/user.js'
  import { onLoad } from '@dcloudio/uni-app'

  const store = useUserStore()

  //1.表单的数据
  const formData = ref({
    account: '111111',
    password: '111111',
  })

  //2.定义 表单的效验规则
  const rules = {
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  }

  // 3.监听表单的提交
  // 表单元素的ref属性
  const accountForm = ref()

  console.log('组件实例 ', accountForm);
  async function onFormSubmit() {
    try {
      // 验证通过
      const formData = await accountForm.value.validate()
      console.log('验证表单', formData);
      // 调用登录接口
      const res = await loginApi(formData)
      console.log('登录成功', res);
      // console.log('token', res.data.data);
      // 记录用户登录成功后的状态
      if (res.code === 200) {
        console.log('200', 200);
        store.setToken(res.data)
        uni.switchTab({
          url: '/pages/task/index'
        })

      } else {

      }
    } catch (err) {
      //TODO 
      console.log('验证失败', err);
    }

  }

  //   // 回跳地址
  const redirectUrl = ref({})

  // 跳转其他地址

  const roueType = ref('')

  onLoad((query) => {
    redirectUrl.value = decodeURIComponent(query.redirectUrl)
    roueType.value = query.roueType

  })

  // 监听表单提交
  async function onformSubmit() {
    try {
      if (roueType.value === 'switch') {
        uni.switchTab({
          url: redirectUrl.value,
        })
      } else {
        uni.redirectTo({
          url: redirectUrl.value
        })
      }
    } catch (e) {
      //TODO handle the exception   
      console.log('验证错误', e);
    }

  }
</script>

<style lang="scss" scoped>
  @import './styles.scss';
</style>